jQuery(document)
		.ready(function() {
			//alert("calling ready");
				var text;
				var coordText;
				var typesText;
				var start = 1;
				var stop = 10;
				var startCoords = 1;
				var stopCoords = 10;
				var startTypes=1;
				var stopTypes=10;
				var totalCoords = 50;
				var totalSources = 40;
				var totalSourcesTypes =60;
				var itemsPerPage = 100;
				var keywords;

				var path = location.pathname;
				var page = path.substring(path.lastIndexOf("/") + 1,
						path.length);
				var root_url = 'http://www.dasregistry.org/';// "http://localhost:8080/dasregistry/";//'http://www.dasregistry.org/';//'http://localhost:8080/dasregistry/';//change
																// this to
																// http://www.dasregistry.org/
				var server_url = root_url + 'das/sources?';
				var base_url = root_url + 'das/sources?';
				var coordinates_server_url = root_url + 'das/coordinatesystem?';
				var coordinates_server_base_url = root_url + 'das/coordinatesystem?';

				var parameters = '';// store the parameters from a request to
									// cope with authority etc from coordsys
									// page links

				var sourcesObjects;// instead of making two calls one to find
									// the total and one to display we can reuse
									// these objects
				var coordinatesObjects;

				var previousTotal = undefined;

				var caps = new Array();
				caps[0] = "sources";
				caps[1] = "stylesheet";
				caps[2] = "features";
				caps[3] = "types";
				caps[4] = "sequence";
				caps[5] = "entry_points";
				caps[6] = "alignment";
				caps[7] = "structure";
				caps[8] = "interaction";
				caps[9] = "unknown-segment";
				caps[10] = "unknown-feature";
				caps[11] = "error-segment";
				caps[12] = "maxbins";
				caps[13] = "cors";
				caps[14] = "feature-by-id";
				caps[15] = "adjacent-feature";
				caps[16] = "format";

				
				function getRootURL(queryURI){
					//alert("calling getRootURL");
//					if(queryURI.indexOf("sources")>1){
//						return queryURI;
//					}
					var indexOfLastSlash=queryURI.lastIndexOf("/");
					var rootURL=queryURI.substring(0,indexOfLastSlash);
					var found=0;
					//if queryuri doesn't contain a command just return the queryuri
					for(var i=0;i<caps.length; i++){
						//alert(rootURL.indexOf(caps[i]));
					if(queryURI.indexOf(caps[i])>0){
						found=1;
					}
					
					}
					//if no command found just return the uri don't chop it
					if(found==0){
						return queryURI;
					}
				//alert('rootUrl='+rootURL);	
				return rootURL;	
				}
				
				function getCoordinateUri(coordinateUri){
					var lastSlash=coordinateUri.lastIndexOf("/");
					var uri=coordinateUri.substring(lastSlash+1,coordinateUri.length);
					return uri;
				}

				/**
				 * This function will be executed in case of error
				 */
				var error_response = function() {
					//alert('Bad response, Wrong URL?, No Sequence XML?');
					text='<font color=\"red\">The search service is down please use the search functionality at <a href="listServices.jsp\">List Sources</a> instead</font>';
					$("#sourcesDiv").html(text);
					$("#coordinatesDiv").html(text);
					$("#ajaxLoaderSources").html('');
					$("#ajaxLoaderCoordinates").html('');
					
				};

				/**
				 * This function print the Sources uri and title
				 */
				var response = function(res, divId) {
					//alert('calling response method');
					// var total=res.total;
					// text+="total="+total;
					// text = '<link rel=\"stylesheet\" type=\"text/css\"
					// href=\"stylesheet.css\" />';
					text = '';// reset the data
					text += '<div id=\"table\"><table id=\"list\"class=\"dastable\">';
					// get info on sources size from sources attr
					totalSources = res.total;

					// print headers

					text += '<tr class="row0">';

					text += '<td><b>pos</pos></td>';
					text += '<td><b>id</b></td>';

					// text +='<td><b>clients</b></td>';

					text += '<td><b>';
					text += 'nickname';

					text += '</b></td>';
					text+='<td><b>status</b></td>';

					// text +='<td><b>';
					// text += 'status';
					// text +='</b></td>';

					text += '<td><b>';
					text += 'description';
					text += '</b></td>';

					text += '<td colspan=\'' + caps.length + '\'>Capabilities</td>';

					text += '<td><b>types';
					text += '</b></td>';

					text += '<td>Specification</td>';
					text += '<td>Project</td>';
					text += '<td>coordinateSystem</td>';
					text += '</tr>';

					var row = 'row0';
					if(res.SOURCE==undefined || res.SOURCE.length==0){
						$("#ajaxLoaderSources").html('');
						return text="No sources returned for this query";
					}else{
					for ( var i = 0; i < res.SOURCE.length; i++) {

						// need to find the number of coordinate systems for
						// this source to see how many rowspans tds need to be

						var coordinates = res.SOURCE[i].VERSION[0].COORDINATES;
						if (coordinates) {
							var numberOfCoords = coordinates.length;
							var rowspan = 1;
							if (numberOfCoords) {
								rowspan = numberOfCoords;
							}
						}
						
						var propMap=createPropertyMap(res.SOURCE[i].VERSION[0].PROP);
						
						//get the number of days before deletion if specified
						//if not then valid else invalid
						var daysBeforeDeletion=60;
						if(propMap['daysBeforeDeletion']){
						daysBeforeDeletion=propMap['daysBeforeDeletion'];	
						//alert(daysBeforeDeletion);
						}
						
						var versionUri=res.SOURCE[i].VERSION[0].uri;
						var sourceId=res.SOURCE[i].uri;
						// alert('number of coords='+numberOfCoords);

						for ( var l = 0; l < rowspan; l++) {

							if (i % 2 == 0) {
								row = 'row1';
							} else {
								row = 'row0';
							}
							text += '<tr class=\"' + row + '\">';
							var position = start + i;
							if (l == 0) {// only do this loop once for a
											// source
								text += '<td rowspan=\'' + rowspan + '\'>'
										+ position + '</td>';
								text += '<td rowspan=\'' + rowspan + '\'>'
										+ res.SOURCE[i].uri;
								
								text+='<div id=\"dassourceactions\" title=\"show details\"><a href=\'showdetails.jsp?auto_id='+sourceId+'\'>';
									text+='<img src=\"img/messagebox_info16x16.png\" border=\"0\"/></a></div>';	
									text+='<div id=\"dassourceactions\" title=\"validate\"><a href=\'validateServer.jsp?auto_id='+sourceId+'\'>';
									text+='<img src=\"img/ok16x16.png\" border=\"0\"/></a></div>';
									
									text+='<div id=\"dassourceactions\" title=\"send to freind\"><a href=\'sendToFriend.jsp?auto_id='+sourceId+'\'>';
									text+='<img src=\"img/mail_post_to16x16.png\" border=\"0\"/></a></div>';	
									
//							<div id="dassourceactions" title="header=[validate] body=[validate the <%=ds.getNickname()%> server]"><a href="validateServer.jsp?auto_id=<%=ds.getId()%>"> 
//								<img 	src="img/ok16x16.png" border="0" alt="validate"
//								onMouseOver="window.status='validate'; return true;"
//								onMouseOut="window.status=' '; return true;"></a>
//								</div>
//							<div id="dassourceactions" title="header=[send to friend] body=[notify a friend about the <%=ds.getNickname()%> server]">
//								<a href="sendToFriend.jsp?auto_id=<%=ds.getId()%>"> 
//								<img src="img/mail_post_to16x16.png" boder="0" alt="edit"
//								onMouseOver="window.status='send to friend'; return true;"
//								onMouseOut="window.status=' '; return true;"></a>
//								</div>
								
								
								
								
										text+= '</td><td rowspan=\'' + rowspan
										+ '\'>' + res.SOURCE[i].title
										+ '</td>'+
										'<td rowspan=\'' + rowspan
										+ '\'>';
								if(daysBeforeDeletion!=60){
									text+='<a href=\"http://www.dasregistry.org/validateServer.jsp?auto_id='+sourceId+'\" title=\''+daysBeforeDeletion+' days before deletion\'><img src=\"img/messagebox_warning.png\"/>Source down/invalid removal in '+daysBeforeDeletion+' days.</a></td>';
								}
								text+='</td>'+
										'<td rowspan=\'' + rowspan
										+ '\'>'+'<a class=\"clickDescription\"  >Show/Hide</a>'
										+'<div class=\'shortdescription\'>'
										+ '<a href=\"'+res.SOURCE[i].doc_href+'\">Further Information</a> '
										+ res.SOURCE[i].description;
								//	+ res.SOURCE[i].description.substring(0,60)+'...';
										+ '</div></td>';
								

										//chop off the command from the quer_uri oin future will need to get the specific uri as these will be allowed to be different
										var shortQueryUri=getRootURL(res.SOURCE[i].VERSION[0].CAPABILITY[0].query_uri);
								
								for (k = 0; k < caps.length; k++) {
									text += '<td rowspan=\'' + rowspan + '\' class=\'noBorder\'>';
									var cap = caps[k];
									// text+=cap;
									var image = '<img class="valid" src=\"' + 'img/clear16.gif' + '\">';// default
									// color
									// for
									// img
									

										var status = propMap[cap];
										var img = '';

										if ('valid' == status)
											img = 'img/green16.gif';
										if ('probably_valid' == status)
											img = 'img/amber16.gif';
										if ('invalid' == status)
											img = 'img/red16.gif';
										if (img == '')
											img = 'img/clear16.gif';

										
										var test_range='';
										if(coordinates){
										test_range=coordinates[0].test_range;
										}
										
										
										//alert(query_uri);
//										var shortQueryUri=query_uri.replace(cap, "");
//										if((i==0)&&(k==0)){
//											alert(query_uri);
//										alert(shortQueryUri);	
//										}
										text += '<a title=\''+cap+' capability is '+status+'\' href=\"' + getTestUrl(
													shortQueryUri,
													cap,
													test_range) + '\">';
											image = '<img class="valid" src=\"' + img + '\"><\/>';
											
										

									
									text += image + '</td>';

								}
								
								text += '<td rowspan=\'' + rowspan + '\'>';
								
								var idForTypes='no types';
									if(propMap['types']=='valid'){idForTypes=versionUri;//ideally should be just source uri =auto_id but because of mirrored sources need url
									text += '<a class=\"click\"  >Show/Hide Types</a>';
									}
								text += '<div class=\"ajaxTypes\" id=\"' + idForTypes + '\"></div>';
								text += '</td>';// <a
												// class="click">Expand/Contract</a>
								// <div class="ajaxTypes" id="<%=auto_id
								// %>"></div>
								text += '<td rowspan=\'' + rowspan + '\'>'+propMap['spec']+'</td>';
								var projectIcon=propMap['projectIcon'];
								if(projectIcon!=undefined){
								var projectId=projectIcon.substring(projectIcon.indexOf('=')+1);
								
								text += '<td rowspan=\'' + rowspan + '\'><a href=\'http://www.dasregistry.org/showProjectDetails.jsp?project_id='+projectId+'\'\'>'+'<img src=\''+projectIcon+'\'></a></td>';
								}else{
								text+=	'<td rowspan=\'' + rowspan + '\'></td>';
								}	
								}// end of l==0 loop for listing source once as
								// span should take care of filling in the rows
								// below.
							// alert('coordinates length='+coordinates.length);

							if (coordinates == undefined || coordinates == null) {// fill
																					// with
																					// empty
																					// tds
																					// though
																					// technically
																					// why
																					// sources
																					// have
																					// no
																					// coords
																					// is
																					// bad
																					// and
																					// should
																					// be
																					// corrected
																					// -
																					// happening
																					// with
																					// mirrored
																					// sources
																					// only
								text += '<td >' + '</td>' + '<td >' + '</td>'
										+ '<td >'

										+ '</td>' + '<td >'

										+ '</td>' + '<td >'

										+ '</td>';
							} else {

								text += '<td >' + '<a href=\''
										+ coordinates[l].uri + '\'>'
										+ coordinates[l].textContent + '</a>'
										+ '<br/><a href=\''
										+ 'listSources.jsp?coordinateid='+getCoordinateUri(coordinates[l].uri) + '\'>'
										+ ' List Sources' + '</a>'
										+ '</td>';

							}

							text += '</tr>';
						}
						;
					}
					}
					text += '</table></div>';
					$("#sourcesDiv").html(text);// need to set html here as the
												// response from server may take
												// a while
					// $('#sourcesDiv a').click(function(){alert('click now
					// works')});
//					
					$(".click").click(function() {

						$(this).next().toggleClass("ajaxTypesLarge");
						var id = $(this).next().attr("id");
						// alert("id="+id);
							if ((id != undefined) && (id != "")) {
								$(this).next().load("types.jsp" + "?id=" + id);
						}
							});
					
					$(".clickDescription").click(function() {
						$(this).next().toggleClass("longdescription");
						
							});
					
//					$(".shortdescription").hover(function (){
//						$(this).toggleClass("longdescription")
//					
//					});
					// $('a img').tooltip();
					$("#ajaxLoaderSources").html('');
					$('#totalSourcesDiv').html(
							start + '-' + stop + ' of ' + totalSources);
					return text;
				}
					
				
				
				
				
				var typesResponse = function(res, divId) {
					//alert('calling types response method');
					// var total=res.total;
					// text+="total="+total;
					// text = '<link rel=\"stylesheet\" type=\"text/css\"
					// href=\"stylesheet.css\" />';
					typesText = '';// reset the data
					typesText += '<div id=\"table\"><table id=\"list\"class=\"dastable\">';
					// get info on sources size from sources attr
					totalSourcesTypes = res.total;
					//alert('totalSourcesTypes='+totalSourcesTypes);

					// print headers

					typesText += '<tr class="row0">';

					typesText += '<td><b>pos</pos></td>';
					typesText += '<td><b>id</b></td>';

					// typesText +='<td><b>clients</b></td>';

					typesText += '<td><b>';
					typesText += 'nickname';

					typesText += '</b></td>';
					typesText+='<td><b>status</b></td>';

					// text +='<td><b>';
					// text += 'status';
					// text +='</b></td>';

					typesText += '<td><b>';
					typesText += 'description';
					typesText += '</b></td>';

					typesText += '<td colspan=\'' + caps.length + '\'>Capabilities</td>';

					typesText += '<td><b>types';
					typesText += '</b></td>';

					typesText += '<td>Specification</td>';
					typesText += '<td>Project</td>';
					typesText += '<td>coordinateSystem</td>';
					typesText += '</tr>';

					var row = 'row0';
					if(res.SOURCE==undefined || res.SOURCE.length==0){
						$("#ajaxLoaderTypes").html('');
						return typesText="No sources returned for this query";
					}else{
					for ( var i = 0; i < res.SOURCE.length; i++) {

						// need to find the number of coordinate systems for
						// this source to see how many rowspans tds need to be

						var coordinates = res.SOURCE[i].VERSION[0].COORDINATES;
						if (coordinates) {
							var numberOfCoords = coordinates.length;
							var rowspan = 1;
							if (numberOfCoords) {
								rowspan = numberOfCoords;
							}
						}
						
						var propMap=createPropertyMap(res.SOURCE[i].VERSION[0].PROP);
						
						//get the number of days before deletion if specified
						//if not then valid else invalid
						var daysBeforeDeletion=60;
						if(propMap['daysBeforeDeletion']){
						daysBeforeDeletion=propMap['daysBeforeDeletion'];	
						//alert(daysBeforeDeletion);
						}
						
						var versionUri=res.SOURCE[i].VERSION[0].uri;
						var sourceId=res.SOURCE[i].uri;
						// alert('number of coords='+numberOfCoords);

						for ( var l = 0; l < rowspan; l++) {

							if (i % 2 == 0) {
								row = 'row1';
							} else {
								row = 'row0';
							}
							typesText += '<tr class=\"' + row + '\">';
							var position = startTypes + i;
							if (l == 0) {// only do this loop once for a
											// source
								typesText += '<td rowspan=\'' + rowspan + '\'>'
										+ position + '</td>';
								typesText += '<td rowspan=\'' + rowspan + '\'>'
										+ res.SOURCE[i].uri;
								typesText+='<div id=\"dassourceactions\" title=\"show details\"><a href=\'showdetails.jsp?auto_id='+sourceId+'\'>';
								typesText+='<img src=\"img/messagebox_info16x16.png\" border=\"0\"/></a></div>';	
								typesText+='<div id=\"dassourceactions\" title=\"validate\"><a href=\'validateServer.jsp?auto_id='+sourceId+'\'>';
								typesText+='<img src=\"img/ok16x16.png\" border=\"0\"/></a></div>';
								
								typesText+='<div id=\"dassourceactions\" title=\"send to freind\"><a href=\'sendToFriend.jsp?auto_id='+sourceId+'\'>';
								typesText+='<img src=\"img/mail_post_to16x16.png\" border=\"0\"/></a></div>';
								typesText+= '</td><td rowspan=\'' + rowspan
										+ '\'>' + res.SOURCE[i].title
										+ '</td>'+
										'<td rowspan=\'' + rowspan
										+ '\'>';
								if(daysBeforeDeletion!=60){
									typesText+='<a href=\"http://www.dasregistry.org/validateServer.jsp?auto_id='+sourceId+'\" title=\''+daysBeforeDeletion+' days before deletion\'><img src=\"img/messagebox_warning.png\"/>Source down/invalid removal in '+daysBeforeDeletion+' days.</a></td>';
								}
								typesText+='</td>'+
										'<td rowspan=\'' + rowspan
										+ '\'>'+'<a class=\"clickDescription\"  >Show/Hide</a>'
										+'<div class=\'shortdescription\'>'
										+ '<a href=\"'+res.SOURCE[i].doc_href+'\">Further Information</a> '
										+ res.SOURCE[i].description;
								//	+ res.SOURCE[i].description.substring(0,60)+'...';
										+ '</div></td>';
								

								
								
								for (k = 0; k < caps.length; k++) {
									typesText += '<td rowspan=\'' + rowspan + '\' class=\'noBorder\'>';
									var cap = caps[k];
									// text+=cap;
									var image = '<img class="valid" src=\"' + 'img/clear16.gif' + '\">';// default
									// color
									// for
									// img
									for (j = 0; j < res.SOURCE[i].VERSION[0].PROP.length; j++) {

										var status = res.SOURCE[i].VERSION[0].PROP[j].value;
										var img = '';

										if ('valid' == status)
											img = 'img/green16.gif';
										if ('probably_valid' == status)
											img = 'img/amber16.gif';
										if ('invalid' == status)
											img = 'img/red16.gif';
										if (img == '')
											img = 'img/clear16.gif';

										var capName = res.SOURCE[i].VERSION[0].PROP[j].name;
										var test_range='';
										if(coordinates){
										test_range=coordinates[0].test_range;
										}
										
										if (capName == cap) {
								
											var shortQueryUri=getRootURL(res.SOURCE[i].VERSION[0].CAPABILITY[0].query_uri);

											typesText += '<a title=\''+capName+' capability is '+status+'\' href=\"' + getTestUrl(
													shortQueryUri,
													cap,
													test_range) + '\">';
											image = '<img class="valid" src=\"' + img + '\"><\/>';
											break;
										}

									}
									typesText += image + '</td>';

								}
								
								typesText += '<td rowspan=\'' + rowspan + '\'>';
								
								var idForTypes='no types';
									if(propMap['types']=='valid'||propMap['types']=='probably_valid'){idForTypes=versionUri;//ideally should be just source uri =auto_id but because of mirrored sources need url
									typesText += '<a class=\"clickTypes\"  >Show/Hide Types</a>';
									}
								typesText += '<div class=\"ajaxTypes\" id=\"' + idForTypes + '\"></div>';
								typesText += '</td>';// <a
												// class="click">Expand/Contract</a>
								// <div class="ajaxTypes" id="<%=auto_id
								// %>"></div>
								typesText += '<td rowspan=\'' + rowspan + '\'>'+propMap['spec']+'</td>';
								var projectIcon=propMap['projectIcon'];
								if(projectIcon!=undefined){
								var projectId=projectIcon.substring(projectIcon.indexOf('=')+1);
								
								typesText += '<td rowspan=\'' + rowspan + '\'><a href=\'http://www.dasregistry.org/showProjectDetails.jsp?project_id='+projectId+'\'\'>'+'<img src=\''+projectIcon+'\'></a></td>';
								}else{
								typesText+=	'<td rowspan=\'' + rowspan + '\'></td>';
								}	
								}// end of l==0 loop for listing source once as
								// span should take care of filling in the rows
								// below.
							// alert('coordinates length='+coordinates.length);

							if (coordinates == undefined || coordinates == null) {// fill
																					// with
																					// empty
																					// tds
																					// though
																					// technically
																					// why
																					// sources
																					// have
																					// no
																					// coords
																					// is
																					// bad
																					// and
																					// should
																					// be
																					// corrected
																					// -
																					// happening
																					// with
																					// mirrored
																					// sources
																					// only
								typesText += '<td >' + '</td>' + '<td >' + '</td>'
										+ '<td >'

										+ '</td>' + '<td >'

										+ '</td>' + '<td >'

										+ '</td>';
							} else {

								typesText += '<td >' + '<a href=\''
										+ coordinates[l].uri + '\'>'
										+ coordinates[l].textContent + '</a>'
										+ '<br/><a href=\''
										+ 'listSources.jsp?coordinateid='+getCoordinateUri(coordinates[l].uri) + '\'>'
										+ ' List Sources' + '</a>'
										+ '</td>';

							}

							typesText += '</tr>';
						}
						;
					}
					}
					typesText += '</table></div>';
					$("#typesDiv").html(typesText);// need to set html here as the
												// response from server may take
												// a while
					// $('#sourcesDiv a').click(function(){alert('click now
					// works')});
//					
					$(".clickTypes").each(function() {

						$(this).next().toggleClass("ajaxTypes");
						var id = $(this).next().attr("id");
						// alert("id="+id);
						//alert("typesWithKeywords.jsp" + "?id=" + id+ "&keywords="+keywords);
							if ((id != undefined) && (id != "")) {
								
								$(this).next().load("typesWithKeywords.jsp" + "?id=" + id+ "&keywords="+keywords);
						}
							});
					
					$(".clickDescription").click(function() {
						$(this).next().toggleClass("longdescription");
						
							});
					
//					$(".shortdescription").hover(function (){
//						$(this).toggleClass("longdescription")
//					
//					});
					// $('a img').tooltip();
					$("#ajaxLoaderTypes").html('');
					$('#totalTypesDiv').html(
							startTypes + '-' + stopTypes + ' of ' + totalSourcesTypes);
					return typesText;
				}
				//creat a map for inspecting properties easily for the values we want rather than looping all the time
				function createPropertyMap(properties){
					var map=new Object();
					if(properties.length>0 && properties!=null && properties!=undefined){
					for(var propIndex=0;propIndex<properties.length; propIndex++){
					var name=properties[propIndex].name;
					var value=properties[propIndex].value;
					map[name]=value;
					//alert(name +'='+value);
					}
					}
					return map;
				}

				function getTestUrl(baseuri, command, testCode) {
					var testurl;
					var extension;
					// alert(baseuri+' ' +command+' '+testCode);
					//should change this to get the test url from the das/sources/dsn/capabilities uri?? will this confuse clients?
					if (command == "sources") {
						testurl = baseuri;
						return testurl;
					}
					
					if (command == "stylesheet") {
						extension = command;
					}
					
					if (command == "features") {
						extension = command + "?segment=" + testCode;
					}
					
					if (command == "types") {
						extension = command;
					}
					
					if (command == "sequence") {
						extension = command + "?segment=" + testCode;
					}
					
					if (command == "entry_points") {
						extension = command;
					}
					
					if (command == "alignment") {
						extension = command + "?query=" + testCode;
					}
					
					if (command == "structure") {
						extension = command + "?query=" + testCode;
					}
					
					if (command == "interaction") {
						extension = command + "?interactor=" + testCode;
					}
					
					if (command == "unknown-segment") {
						extension = "features" + "?segment="
								+ 'invalidTestCode' + ":1,1000";
					}
					
					if (command == "unknown-feature") {
						extension = "features" + "?feature_id="
								+ 'invalidTestCode';
					}
					
					if (command == "error-segment") {
						extension = "features" + "?segment="
								+ 'invalidTestCode' + ":1,1000";
					}
					
					if (command == "maxbins") {
						extension = "features" + "?segment=" + testCode
								+ ";maxbins=1";
					}
					if(command == "feature-by-id"){
						extension = "features" + "?feature_id=";
					}
					

					testurl = baseuri +'\/'+extension;

					return testurl;
				}

				/**
				 * This function print the coordinates uri and title
				 */
				var responseCoordinates = function(res) {
					// alert("response coords");
					// var total=res.total;
					// text+="total="+total;
					// coordtText = '<link rel=\"stylesheet\" type=\"text/css\"
					// href=\"stylesheet.css\" />';
					coordText = '';
					coordText += '<div id=\"table\"><table id=\"listCoordinates\"class=\"dastable\">';
					// get info on sources size from sources attr
					totalCoordinates = res.total;

					var row = 'row0';
					if(res.COORDINATES==undefined || res.COORDINATES.length==0 || res.total==0){
						$("#ajaxLoaderCoordinates").html('');
					return coordText="No coordinates returned for this query";
					}
					for ( var i = 0; i < res.COORDINATES.length; i++) {
						if (i % 2 == 0) {
							row = 'row1';
						} else {
							row = 'row0';
						};
						var taxid = res.COORDINATES[i].taxid;
						if (taxid == undefined) {
							taxid = '';
						}
						coordText += '<tr class=\"' + row + '\"><td>'
						+ '<a href=\'' + res.COORDINATES[i].uri
						+ '\' target="_blank\">'
								+ res.COORDINATES[i].textContent
								+'</a>' + '</td>'
								+'<td>'
								+ '<a href=\''
								+ 'listSources.jsp?coordinateid='+getCoordinateUri(res.COORDINATES[i].uri) + '\'>'
								+ ' List Sources with CoordinateSystem' + '</a>'
								+'</td>'
								+'<td>'+ taxid + '</td><td>'
								+ res.COORDINATES[i].source + '</td><td>'
								+ res.COORDINATES[i].authority + '</td>'
								+ '</tr>';
					}

					coordText += '</table></div>';
					$("#coordinatesDiv").html(coordText);// need to set html
															// here as the
															// response from
															// server may take a
															// while
					$("#ajaxLoaderCoordinates").html('');
					$('#totalCoordinatesDiv').html(
							startCoords + '-' + stopCoords + ' of '
									+ totalCoordinates);
					return coordText;
				};

				/**
				 * Initialisation function for pagination
				 */

				function handlePaginationClick(new_page_index,
						pagination_container) {
					// This selects 20 elements from a content array
					if ($('#ajaxLoaderSources').val() == '') {
						$("#ajaxLoaderSources").html(
								'<img src=\"' + 'img/ajax-loader.gif' + '\">');
					}
					loadSources(new_page_index);

				}
				
				function handleTypesPaginationClick(new_page_index,
						pagination_container) {
					// This selects 20 elements from a content array
					if ($('#ajaxLoaderTypes').val() == '') {
						$("#ajaxLoaderTypes").html(
								'<img src=\"' + 'img/ajax-loader.gif' + '\">');
					}
					loadTypes(new_page_index);

				}

				function handleCoordinatesPaginationClick(new_page_index,
						pagination_container) {
					// This selects 20 elements from a content array
					if ($('#ajaxLoaderCoordinates').val() == '') {
						$("#ajaxLoaderCoordinates").html(
								'<img src=\"' + 'img/ajax-loader.gif' + '\">');
					}
					loadCoordinates(new_page_index);

				}

				function loadSources(new_page_index) {
					// alert(new_page_index);
					start = (new_page_index * itemsPerPage) + 1;
					stop = start + itemsPerPage - 1;
					var d = new Date();

					JSDAS.sources(escape(server_url + '&rows=' + start + '-'
							+ stop + '&neverused=' + d.getTime()), response,
							error_response);
					$.ajaxSetup( {
						cache : false
					});
				}
				
				function loadTypes(new_page_index) {
					// alert(new_page_index);
					startTypes = (new_page_index * itemsPerPage) + 1;
					stopTypes = startTypes + itemsPerPage - 1;
					var d = new Date();

					JSDAS.sources(escape(types_server_url + '&rows=' + startTypes + '-'
							+ stopTypes + '&neverused=' + d.getTime()), typesResponse,
							error_response);
					$.ajaxSetup( {
						cache : false
					});
				}
				function loadCoordinates(new_page_index) {
					// alert(new_page_index);
					startCoords = (new_page_index * itemsPerPage) + 1;
					stopCoords = startCoords + itemsPerPage - 1;
					var d = new Date();

					JSDAS.coordinate_systems(escape(coordinates_server_url
							+ '&rows=' + startCoords + '-' + stopCoords
							+ '&neverused=' + d.getTime()),
							responseCoordinates, error_response);
					$.ajaxSetup( {
						cache : false
					});
				}

				
				//using action="NavigateSources.jsp" now means we dont need this extra stuff
				//ajax still works for pagination
				
				// $("#submit").click(submitKeywords);
				//$("#submit").click(forwardToNavigateSources);

				// of coming from another page than our main sources search we
				// need to get the keywords from the parameters and pass them to
				// our main search page and search.
				// if on sources navigation page we can just ignore the ke
//				function forwardToNavigateSources() {
//					var keywords = $('#keywords').val();
//					// alert('keywords');
//					var stringKeywords = 'NavigateSources.jsp?keywords=' + keywords;
//					// alert('changed'+stringKeywords);
//					$.get(stringKeywords);
//					// alert(window.location);
//					window.location = stringKeywords;
//					// $('.result').html(data);
//					// alert('Load was performed.');
//
//				}

				function submitKeywords() {
					if ($('#ajaxLoaderSources').val() == '') {
						$("#ajaxLoaderSources").html(
								'<img src=\"' + 'img/ajax-loader.gif' + '\">');
					}
					if ($('#ajaxLoaderCoordinates').val() == '') {
						$("#ajaxLoaderCoordinates").html(
								'<img src=\"' + 'img/ajax-loader.gif' + '\">');
					}
					keywords = $(document).getUrlParam("keywords");
					if (keywords == '' || keywords == null || keywords == undefined) {
						// alert('keywords undefined');
						parameters = parameters.replace('keywords=', ''); // if
																			// no
																			// keywords
																			// specified
																			// get
																			// rid
																			// of
																			// the
																			// parameter
																			// so
																			// all
																			// results
																			// returned
					}
					server_url = base_url + parameters;// '&keywords='+keywords;
					coordinates_server_url = coordinates_server_base_url
							+ parameters;
					types_server_url = base_url +parameters.replace('keywords=', 'typeskeywords=');// '&keywords='+keywords;
					 //alert('types_server_url='+types_server_url);
					// need a dummy run first to set the total and then run the
					// normal method
					// need to wait for getTotal to return before running the
					// rest??!!
					getTotalSources();
					getTotalCoordinates();
					if(keywords){//if a keyword has been specified search types - if not do not give a types response as this will be the same as the sources response
					getTotalSourcesMatchingTypes();
					}
				}

				$('#keywords').keyup(function(e) {
					//alert('setting keyup');
					if (e.keyCode == 13) {
						//alert('keyup');
						// if pressed return after inserting into search then
						// ignore other paremeters and get keywords
						// $("#form1").submit();
						// forwardToNavigateSources;
					}
				});

				var responseToGetTotal = function(res) {

					totalSources = res.total;
					// if total is undefined then no sources returned
					// display this

					// if this is the first call with keyword then we can reuse
					// the object rather than do another request- set up methods
					// to do this
					// , maybe just need an if first flag in write sources
					// method use the sourcesObject then reset to not first so
					// we can make requests thereafter.
					
					if (totalSources == 0) {

						$('#sourcesDiv').html(
								'No sources returned for this query.');
						$('#ajaxLoaderSources').html('');
					} else {
						// var id=res.SOURCE[0].uri;

						$("#Sources-Pagination").pagination(totalSources, {
							items_per_page : itemsPerPage,
							callback : handlePaginationClick,
							link_to : "#Sources-Pagination"
						});
					}

					// alert('total in gettotal='+total+id);

				};
				
				var responseToGetTotalTypes = function(res) {

					totalSourcesTypes = res.total;
					// if total is undefined then no sources returned
					// display this

					// if this is the first call with keyword then we can reuse
					// the object rather than do another request- set up methods
					// to do this
					// , maybe just need an if first flag in write sources
					// method use the sourcesObject then reset to not first so
					// we can make requests thereafter.
					
					if (totalSourcesTypes == 0) {

						$('#TypesDiv').html(
								'No sources returned for this query.');
						$('#ajaxLoaderTypes').html('');
					} else {
						// var id=res.SOURCE[0].uri;

						$("#Types-Pagination").pagination(totalSourcesTypes, {
							items_per_page : itemsPerPage,
							callback : handleTypesPaginationClick,
							link_to : "#Types-Pagination"
						});
					}


				};


				// Find ALL <form> tags on your page
				// can't do this as stops login etc when this is in header!!!
				// $("form").submit(function() {
				// //submitKeywords;
				// return false;
				// });

				var responseToGetTotalCoordinates = function(res) {

					totalCoordinates = res.total;
					// alert("total coordinates="+totalCoordinates);
					// if total is undefined then no sources returned
					// display this
					if (totalCoordinates == 0) {
						$('#coordinatesDiv').html(
								'No coordinates returned for this query.');
						$("#ajaxLoaderCoordinates").html('');
					} else {
						// var id=res.SOURCE[0].uri;
						$("#Coordinates-Pagination")
								.pagination(
										totalCoordinates,
										{
											items_per_page : itemsPerPage,
											callback : handleCoordinatesPaginationClick,
											link_to : "#Coordinates-Pagination"
										});
					}
					// alert('total in gettotal='+total+id);

				};

				function getTotalSources() {
					// alert("calling get total");
					var d = new Date();
					//start and stop don't effect total so just return 1 source- need to change this so we use same start and stop and then use objects rather than running request again
					JSDAS.sources(escape(server_url + '&rows=' + 1 + '-'
							+ 1 + '&neverused=' + d.getTime()),
							responseToGetTotal, error_response);

					// alert("ending get total");
				}
				
				function getTotalSourcesMatchingTypes() {
					// alert("calling get total");
					var d = new Date();
					//start and stop don't effect total so just return 1 source- need to change this so we use same start and stop and then use objects rather than running request again
					JSDAS.sources(escape(types_server_url + '&rows=' + 1 + '-'
							+ 1 +'&neverused=' + d.getTime()),
							responseToGetTotalTypes, error_response);

					// alert("ending get total");
				}
				

				function getTotalCoordinates() {
					// alert("calling get total coordinates");
					var d = new Date();
					JSDAS.coordinate_systems(escape(coordinates_server_url
							+ '&rows=' + 1 + '-' + 1 + '&neverused='
							+ d.getTime()), responseToGetTotalCoordinates,
							error_response);

					// alert("ending get total");
				}
				

				$('#hideSources').click(function() {
					$('#sourcesDiv').hide('slow', function() {

					});
				});
				$('#showSources').click(function() {
					$('#sourcesDiv').show('slow', function() {

					});
				});

				$('#hideCoords').click(function() {
					$('#coordinatesDiv').hide('slow', function() {

					});
				});
				$('#showCoords').click(function() {
					$('#coordinatesDiv').show('slow', function() {

					});
				});

				// set background to current page in menu
				$(function() {
					// var path = location.pathname.substring(13);//dasregistry/
					// means jump this number of letters of path to get
					// page..should be a better way?
					// alert('page='+page);
					if (page)
						$('#menu ul li a[href$="' + page + '"]').attr('class',
								'active');
				});

				$(function() {

					var paramString = location.search;
					// alert('calling blank function for page');
					if (page == "NavigateSources.jsp") {// only send request to
														// registry if request
														// is for the search
														// page
						// alert('location='+location);
						// alert('path='+path);
						parameters = paramString.substring(1);// set the
																// params so if
																// a page
																// request we
																// can get the
																// right data
																// and cho
						// alert('paramString='+paramString);
						var value = $(document).getUrlParam("keywords");
						// if(value==''){
						// parameters=parameters.replace('keywords=', ''); //if
						// no keywords specified get rid of the parameter so all
						// results returned
						// }
						// alert("nav sources"+value);
						// if ( value){//only submit if a keyword has been put
						// in and search pressed
						$('#keywords').val(value);// set the value in diplay
													// for the current page as
													// could have come from
													// another page
						submitKeywords();
					}
					// $('#menu ul li a[href$="' + path + '"]').attr('class',
					// 'active');
				});
				
				
				   // use this to reset a single form
				   $("#reset").click(function() {
					   //alert('reset pressed');
				     $('#capabilities').val('any');
				     $('#CSName').val('any');
				     $('#CSTypes').val('any');
				     $('#labels').val('any');
				     $('#organism').val('any');
				     $('#spec').val('any');
				   });
				   
//				 $(".ajaxTypes").each(function(){
//					 var id=$(this).attr("id");
//					 if((id!="udefined")&&(id!="")){
//					 $(this).load("types.jsp"+"?id="+id );
//					 
//					 }
//				 });
//				 
				 
//				 $(".click").click(function(){
//				 		
//				 		$(this).next().toggleClass("ajaxTypesLarge");
//				 		//$(this).next().slideToggle();
//				 		}
//				 	);

				// $('a').live('click', function to call)

				// $('a').load(function(){
				// $("a").click(function() {
				// alert("Hello world!");
				// });
				// // $('a').tooltip();
				// });

				// $(function(){
				// $("a").click(function() {
				// alert("Hello world!");
				// });
				// });

				// $(".click").click(function(){
				//			 		
				// $(this).next().toggleClass("ajaxTypesLarge");
				// //$(this).next().slideToggle();
				// }
				// );
				
				
//				for (var key in propMap) {
//			    alert([key, propMap[key]].join("\n\n"));
//			}

//				$(".ajaxTypes").each(function() {
//				
//				var id = $(this).attr("id");
//				// alert("id="+id);
//					if ((id != "udefined") && (id != "")) {
//						$(this).load("types.jsp" + "?id=" + id);// need
//																// to
//																// change
//																// this
//																// if
//																// not
//																// on
//																// registry
//																// server
//																// to
//																// www.dasregistry.org/types.jsp
//
//					}
//				});
			});